﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class SchoolPledges : Acms.AcmsControls.ContentControls.Admin.BaseCustomAdminControl
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        grid.NeedDataSource += new GridNeedDataSourceEventHandler(grid_NeedDataSource);
        download.DataBinding += new EventHandler(download_DataBinding);
    }

    void download_DataBinding(object sender, EventArgs e)
    {
        download.DataSource = GetData();   
    }

    void grid_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
    {
        grid.DataSource = GetData();   
    }

    protected object GetData()
    {
        ClimateChangeChampionsData.DataContext context = new ClimateChangeChampionsData.DataContext();
        var data =
                   from pledge in context.Pledges
                   group pledge by pledge.UserId into groupedPledge
                   join user in context.Users on groupedPledge.Key equals user.Id
                   join schoolName in context.UserCustomProperties on new { Id = user.Id, Name = "School Name" } equals new { Id = schoolName.UserId, Name = schoolName.Name }
                   join pt in context.UserCustomProperties on new { Id = user.Id, Name = "Pledge Text" } equals new { Id = pt.UserId, Name = pt.Name } into leftjoinPt
                   from pledgeText in leftjoinPt.DefaultIfEmpty()
                   select new { Id = groupedPledge.Key, SchoolName = schoolName.Value, AuthenticatedPledges = groupedPledge.Where(p => p.Authenticated == true).Count(), TotalPledges = groupedPledge.Count(), PledgeText = pledgeText != null ? pledgeText.Value : null};
        return data.AsEnumerable();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            GridHyperLinkColumn col = grid.Columns[grid.Columns.Count - 1] as GridHyperLinkColumn;
            if (col != null)
            {
                string viewPledgeListUrl = base.ResolveCustomControlPath("~/PledgeList.ascx?SchoolId={0}");
                col.DataNavigateUrlFormatString = viewPledgeListUrl;
            }

        }
    }
}
